package com.lagou.multipartdatasource.aop;

import com.alibaba.druid.util.StringUtils;
import com.lagou.multipartdatasource.config.DataSourceContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Lazy(false)
@Order(0) // Order设定AOP执行顺序 使之在数据库事务上先执行
public class SwitchDataSourceAOP {

	@Pointcut("@annotation(com.lagou.multipartdatasource.aop.DataAnno)")
	public void pc(){}

	// 这里切到你的方法目录
	@Before("pc()")
	public void process(JoinPoint joinPoint) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		DataAnno dataSourceAnno = method.getAnnotation(DataAnno.class);
		String value = dataSourceAnno.value();

		DataSourceContextHolder.setDbType(StringUtils.isEmpty(value) || value.equals("write")?"updateDataSource":"selectDataSource");
		/*String methodName = signature.getName();
		if (methodName.startsWith("get") || methodName.startsWith("count") || methodName.startsWith("find")
				|| methodName.startsWith("list") || methodName.startsWith("select") || methodName.startsWith("check")) {
			// 读
			DataSourceContextHolder.setDbType("selectDataSource");
		} else {
			// 切换dataSource
			DataSourceContextHolder.setDbType("updateDataSource");
		}*/
	}
}